package com.rinlink.jbcodec.creator;

import com.alibaba.fastjson.JSONObject;
import com.rinlink.jbcodec.exception.AttributePropertyException;
import com.rinlink.jbcodec.exception.FieldValueException;
import com.rinlink.jbcodec.transform.BytesToHexString;
import com.rinlink.jbcodec.transform.Transform;

import java.nio.ByteBuffer;

public class ByteBufferToVariableHexStringCreator extends ByteBufferToObjectCreator {

    @Override
    protected Transform create(JSONObject attr, ByteBuffer data, JSONObject t) {
        String bytes_field = attr.getString("bytes_field");
        if (bytes_field == null)
            throw new AttributePropertyException("bytes_field");
        Integer bytes;
        try {
            bytes = t.getInteger(bytes_field);
            if (bytes == null){
                throw new FieldValueException(bytes_field);
            }
        }catch (Exception e){
            throw new FieldValueException(bytes_field);
        }
        return new BytesToHexString(data,bytes);
    }

}
